package boun.swe.bob.service;

import boun.swe.bob.entities.User;
import boun.swe.bob.util.RandomPassword;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * User: TTACANSEVER
 */
public class FileUploadController extends BaseController{

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();
        myModel.put("himself", true);
        myModel.put("user", userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId()));
        return new ModelAndView("fileUpload", "model", myModel);
    }



    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();
        MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpServletRequest;
        String fileName = RandomPassword.getRandomString(8);
        File file = new File(httpServletRequest.getRealPath("") + "/user_images/" + fileName + ".jpg");
        try {
            if(null != file) {
                request.getFile("file").transferTo(file);
                User user = getLoggedInUser(httpServletRequest);
                user.setImage(fileName + ".jpg");
                userDao.update(user);
                httpServletRequest.getSession().setAttribute("user", user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        myModel.put("himself", true);
        myModel.put("user", userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId()));
        myModel.put("homefeeds", homeFeedDao.findHomeFeedsByUserId(getLoggedInUser(httpServletRequest).getUserId(),5));
        return new ModelAndView("homePage", "model", myModel);
    }


}
